﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using CommonServiceLocator.WindsorAdapter;
using HibernatingRhinos.Profiler.Appender.NHibernate;
using log4net.Config;
using Microsoft.Practices.ServiceLocation;
using MvcMall.AdminPortal.CastleWindsor;
using MvcMall.AdminPortal.Controllers.Home;
using MvcMall.Data.NHibernateMaps;
using MvcMall.Framework.Extensions;
using SharpArch.Data.NHibernate;
using SharpArch.Web.Castle;
using SharpArch.Web.ModelBinder;
using SharpArch.Web.NHibernate;

namespace MvcMall.AdminPortal
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

        }

        protected void Application_Start()
        {
            NHibernateProfiler.Initialize();
            XmlConfigurator.Configure();
            InitializeServiceLocator();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        private WebSessionStorage webSessionStorage;
        public override void Init()
        {
            base.Init();

            // The WebSessionStorage must be created during the Init() to tie in HttpApplication events
            webSessionStorage = new WebSessionStorage(this);
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            // Only initialise the NHibernate Sessions for a non static, i.e. Controller Action request
            if (!Request.IsStaticFile())
            {
                NHibernateInitializer.Instance().InitializeNHibernateOnce(InitializeNHibernateSession);
            }
        }

        private void InitializeNHibernateSession()
        {
            NHibernateSession.Init(
                webSessionStorage,
                new[] { Server.MapPath("~/bin/MvcMall.Data.dll") },
                new AutoPersistenceModelGenerator().Generate(),
                Server.MapPath("~/NHibernate.config"));
        }

        protected virtual void InitializeServiceLocator()
        {
            IWindsorContainer container = new WindsorContainer();
            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(container));

            container.RegisterControllers(typeof(HomeController).Assembly);
            ComponentRegistrar.AddComponentsTo(container);

            ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(container));
        }
    }
}